package com.honghe.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.honghe.constant.MessageConstant;
import com.honghe.dto.DepartmentDTO;
import com.honghe.dto.DepartmentPageDTO;
import com.honghe.entity.Department;
import com.honghe.entity.Doctor;
import com.honghe.exception.DeletionNotAllowedException;
import com.honghe.mapper.DepartmentMapper;
import com.honghe.mapper.DoctorMapper;
import com.honghe.result.PageResult;
import com.honghe.service.DepartmentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DepartmentServiceImpl implements DepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private DoctorMapper doctorMapper;
    /**
     * 分页查询
     * @param departmentPageDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DepartmentPageDTO departmentPageDTO) {
        PageHelper.startPage(departmentPageDTO.getPage(), departmentPageDTO.getPageSize());
        Page<Department> page = departmentMapper.pageQuery(departmentPageDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 更新部门
     * @param departmentDTO
     */
    @Override
    public void update(DepartmentDTO departmentDTO) {
        List<Doctor> doctors = doctorMapper.getByDeptId(departmentDTO.getId());
        if (!doctors.isEmpty()){
            throw new DeletionNotAllowedException(MessageConstant.HAVE_DOCTOR_IN_DEPT);
        }
        Department department = new Department();
        BeanUtils.copyProperties(departmentDTO,department);
        departmentMapper.updateById(department);
    }

    /**
     * 新增部门
     * @param departmentDTO
     */
    @Override
    public void insert(DepartmentDTO departmentDTO) {
        Department department = new Department();
        BeanUtils.copyProperties(departmentDTO,department);
        departmentMapper.insert(department);
    }

    /**
     * 删除部门
     * @param id
     */
    @Override
    public void delete(Long id) {
        List<Doctor> doctors = doctorMapper.getByDeptId(id);
        if (!doctors.isEmpty()){
            throw new DeletionNotAllowedException(MessageConstant.HAVE_DOCTOR_IN_DEPT);
        }
        departmentMapper.deleteById(id);
    }

    /**
     * 根据部门id查询部门
     * @param id
     * @return
     */
    @Override
    public Department getById(Long id) {
        Department department=departmentMapper.getById(id);
        return department;
    }
}
